package com.example.taobaounion.ui.fragment;

import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;
import com.example.taobaounion.model.bean.Histories;
import com.example.taobaounion.model.bean.IBaseInfo;
import com.example.taobaounion.model.bean.SearchRecommend;
import com.example.taobaounion.model.bean.SearchResult;
import com.example.taobaounion.presenter.ISearchPresenter;
import com.example.taobaounion.ui.adapter.LinearItemContentAdapter;
import com.example.taobaounion.ui.custom.TextFlowLayout;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.PresenterManager;
import com.example.taobaounion.utils.SizeUtils;
import com.example.taobaounion.utils.TicketUtils;
import com.example.taobaounion.utils.ToastUtil;
import com.example.taobaounion.utils.keyboardUtil;
import com.example.taobaounion.view.ISearchPageCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class SearchFragment extends BaseFragment implements ISearchPageCallback, TextFlowLayout.OnFlowTextItemClickListener {

    private ISearchPresenter mSearchPresenter;

    @BindView(R.id.search_history_view)
    public TextFlowLayout mHistoriesView;
    @BindView(R.id.search_recommend_view)
    public TextFlowLayout mRecommendView;
    @BindView(R.id.search_recommend_container)
    public View mRecommendContainer;
    @BindView(R.id.search_history_container)
    public View  mHistoriesContainer;
    @BindView(R.id.search_history_delete)
    public View mHistoryDelete;
    @BindView(R.id.search_result_list)
    public RecyclerView mSearchList;

    @BindView(R.id. search_result_container)
    public TwinklingRefreshLayout mRefreshContainer;

    @BindView(R.id. search_btn)
    public TextView mSearchBtn;
    @BindView(R.id. search_clean_btn)
    public ImageView mCleanInputBtn;
    @BindView(R.id. search_input_box)
    public EditText mSearchInputBox;

    private LinearItemContentAdapter mSearchResultAdapter;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initPresenter() {
        mSearchPresenter = PresenterManager.getInstance().getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);
        //获取推荐词
        mSearchPresenter.getRecommendWords();
        //mSearchPresenter.doSearch("毛衣");
        mSearchPresenter.getHistories();
    }

    @Override
    protected void initView(View rootView) {
        setUpState(State.SUCCESS);
        //设置布局管理器
        mSearchList.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置适配器
        mSearchResultAdapter = new LinearItemContentAdapter();
        mSearchList.setAdapter(mSearchResultAdapter);
        //设置刷新控件
        mRefreshContainer.setEnableLoadmore(true);
        mRefreshContainer.setEnableRefresh(false);
        mRefreshContainer.setEnableOverScroll(true);
        mSearchList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull  Rect outRect, @NonNull  View view, @NonNull  RecyclerView parent, @NonNull  RecyclerView.State state) {
                outRect.top= SizeUtils.dip2px(getContext(),1.5f);
                outRect.bottom=SizeUtils.dip2px(getContext(),1.5f);
            }
        });
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_search_layout,container,false);
    }

    @Override
    protected void initListener() {
        mHistoriesView.setOnFlowTextItemClickListener(this);
        mRecommendView.setOnFlowTextItemClickListener(this);

        //发起搜索
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果有内容搜索
                if(hasInput(false)){
                    //发起搜索
                    if (mSearchPresenter != null) {
                        //mSearchPresenter.doSearch(mSearchInputBox.getText().toString().trim());
                        toSearch(mSearchInputBox.getText().toString().trim());
                        keyboardUtil.hide(getContext(),v);
                    }
                }else {
                      //隐藏键盘
                    keyboardUtil.hide(getContext(),v);
                }

                //取消
            }
        });


        mHistoryDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除历史记录
                if (mSearchPresenter != null) {
                    mSearchPresenter.delHistories();
                }
            }
        });
        mRefreshContainer.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                //去加载更多内容
                if (mSearchPresenter != null) {
                    mSearchPresenter.loaderMore();
                }
            }
        });
        mSearchResultAdapter.setOnItemClickListener(new LinearItemContentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(IBaseInfo item) {
                //搜索内容列表被点击了
                TicketUtils.toTicketPage(getContext(),item);//生命周期传getContext就够了,因为当SearchFragment销毁了
                //也就没不会执行这个点击时间,context生命周期随SearchFragment就够了
            }
        });
        //输入框发起搜索的监听
        mSearchInputBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            //当点击搜索执行下面方法
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                LogUtils.d(SearchFragment.this,"actionId-->"+actionId);
                if(actionId== EditorInfo.IME_ACTION_SEARCH&&mSearchPresenter!=null){
                    String keyword = v.getText().toString().trim();
                    //判断拿到的内容是否为空,为空的话直接返回
                    if(TextUtils.isEmpty(keyword)){
                        return false;
                    }
                    LogUtils.d(SearchFragment.this,"input text ---->"+keyword);
                    //不为空则发起搜索
                    //mSearchPresenter.doSearch(keyword);
                    toSearch(keyword);
                }
                return false;
            }
        });

        //输入框内容变化的监听
        mSearchInputBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //当输入框文字发生变化时
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
               //变化时候的通知
                //LogUtils.d(SearchFragment.this,"input_text--->"+s.toString().trim());
                //如果长度不为0，那么显示删除按钮，否则隐藏删除按钮
                mCleanInputBtn.setVisibility(hasInput(true)?View.VISIBLE:View.GONE);
                mSearchBtn.setText(hasInput(false)?"搜索":"取消");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //清除输入框里的内容
        mCleanInputBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchInputBox.setText("");
                //回到历史记录界面
                switch2HistoryPage();
            }
        });
    }

    /**
     * 切换到历史和推荐的页面
     */
    private void switch2HistoryPage(){
        if(mSearchPresenter!=null){
            mSearchPresenter.getHistories();
        }
        if(mHistoriesView.getContentSize()!=0){
            mHistoriesContainer.setVisibility(View.VISIBLE);
        }else {
            mHistoriesContainer.setVisibility(View.GONE);
        }
        if(mRecommendView.getContentSize()!=0){
            mRecommendContainer.setVisibility(View.VISIBLE);
        }else {
            mRecommendContainer.setVisibility(View.GONE);
        }
        //内容要隐藏
        mRefreshContainer.setVisibility(View.GONE);
    }

    private boolean hasInput(boolean containSpace){
        if(containSpace){
            return mSearchInputBox.getText().toString().length() > 0;
        }else {
            return mSearchInputBox.getText().toString().trim().length() > 0;
        }
    }

    //搜索历史记录加载
    @Override
    public void onHistoriesLoaded(Histories histories) {
        LogUtils.d(this,"histories--->"+histories);
        if(histories==null||histories.getHistories().size()==0){
            mHistoriesContainer.setVisibility(View.GONE);
        }else {
            mHistoriesContainer.setVisibility(View.VISIBLE);
            mHistoriesView.setTextList(histories.getHistories());
        }
    }

    @Override
    public void onHistoriesDeleted() {
        //更新历史记录
        if (mSearchPresenter != null) {
            mSearchPresenter.getHistories();
        }

    }

    @Override
    protected void onRetryClick() {
        //重新加载内容
        if (mSearchPresenter != null) {
            mSearchPresenter.reSearch();
        }
    }

    @Override
    public void onSearchSuccess(SearchResult result) {
        setUpState(State.SUCCESS);
        LogUtils.d(this,"result---->"+result);
        //隐藏掉历史记录和推荐
        mRecommendContainer.setVisibility(View.GONE);
        mHistoriesContainer.setVisibility(View.GONE);
        //显示搜索界面
        mRefreshContainer.setVisibility(View.VISIBLE);
        //设置数据
        try {
            mSearchResultAdapter.setData(result.getData().getTbk_dg_material_optional_response()
                    .getResult_list().getMap_data());
        }catch (Exception e){
            e.printStackTrace();
            setUpState(State.EMPTY);
        }


    }

    @Override
    public void onMoreLoaded(SearchResult result) {
        mRefreshContainer.finishLoadmore();
        //加载到更多的结果
        //拿到结果，添加到适配器的尾部
        List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> moreData = result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        mSearchResultAdapter.addData(moreData);
        //提示用户加载到的内容
        ToastUtil.showToast("加载到了"+moreData.size()+"条记录");

    }

    @Override
    public void onMoreLoadedError() {
        mRefreshContainer.finishLoadmore();
        ToastUtil.showToast("网络异常，请稍后重试");
    }

    @Override
    public void onMoreLoadedEmpty() {
        mRefreshContainer.finishLoadmore();
        ToastUtil.showToast("没有更多的数据");
    }

    @Override
    public void onRecommendWordsLoaded(List<SearchRecommend.DataBean> recommendWords) {
        LogUtils.d(this,"recommendWords size --->"+recommendWords.size());
        List<String> recommendKeywords=new ArrayList<>();
        for (SearchRecommend.DataBean item:recommendWords){
            recommendKeywords.add(item.getKeyword());
        }
        if(recommendWords==null||recommendWords.size()==0){
            mRecommendContainer.setVisibility(View.GONE);
        }else {
            mRecommendView.setTextList(recommendKeywords);
            mRecommendContainer.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);

    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    protected void release() {
        if (mSearchPresenter != null) {
            mSearchPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void onFlowItemClick(String text) {
        //发起搜索
        toSearch(text);
    }

    private void toSearch(String text) {
        if(mSearchPresenter!=null){
            mSearchList.scrollToPosition(0);
            mSearchInputBox.setText(text);
            //setFocusable是设置可以获取焦点，但不一定获得；requestFocus是要获取焦点
            mSearchInputBox.setFocusable(true);
            mSearchInputBox.requestFocus();//里面有个构造方法，表示向下移动焦点,他会在指定的mSearchInputBox控件向下方向
            // 移动焦点，比如布局上，一个父布局，他的子布局有一个editText,那么当他执行requestFocus()时，就会往下去获取子布局
            //editText的焦点
            mSearchInputBox.setSelection(text.length());
            mSearchPresenter.doSearch(text);
        }
    }
}
